<?php

class CS_Core
{
	public static $default_controller = 'index';
	public static $default_action = 'index';

	public $data;

	public static function load($class_name)
	{
		$class = str_replace('_', DS, $class_name).EXT;

		if(class_exists($class_name))
		{
			return true;
		} else {
			try {
				if(file_exists(PATH.LIBS.DS.$class))
				{
					require_once(PATH.LIBS.DS.$class);
				} else {
					throw new CS_Error_Exception('The specified class does not exist : '.$class_name);
				}
			} catch(CS_Error_Exception $e)
			{
				$e->printError();
			} catch(Exception $e)
			{
				echo $e->getMessage();
			}
		}
	}

	public function _loadController($controller = null)
	{
		if(empty($controller))
		{
			$controller = $this->default_controller;
		}

		$controller_path = $this->path('core').$controller.DS.'controller'.EXT;

		if(file_exists($controller_path))
		{
			require_once($controller_path);

			// construct the controller and set theme/layout/view
			$controller_class = ucfirst($controller).'Controller';
			$this->controller = new $controller_class;

			if(!isset($this->controller->name) || empty($this->controller->name))
			{
				$this->controller->name = $controller;
			}
		} else {
			try{
				throw new CS_Error_Exception('Invalid Controller');
			} catch(CS_Error_Exception $e)
			{
				$e->printError();
			}
		}
	}

	public function _loadModel()
	{
		$model = new CS_Model;

		$tables = $model->getTableList();

		if(isset($this->controller->useTable) && !empty($this->controller->useTable))
		{
			$table = $this->controller->useTable;
		} else {
			$table = $this->controller->name;
		}

		$model_path = CS_Application::path('core').$table.DS.'model'.EXT;

		if(file_exists($model_path) || in_array($table, $tables))
		{
			require_once($model_path);

			$model_class = ucfirst($table).'Model';

			$this->model = new $model_class;
		} else {
			$this->model = null;
		}

		$this->controller->model =& $this->model;
	}

	public function _loadView($action = null)
	{
		$this->view = new CS_View;
		//$this->view->controller =& $this->controller;

		$this->controller->view =& $this->view;
	}
}
